package com.anolesoft.twelvePlan.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.anolesoft.common.core.domain.LoginUser;
import com.anolesoft.common.core.web.domain.AjaxResult;
import com.anolesoft.twelvePlan.dto.*;
import com.anolesoft.twelvePlan.service.GongDuanPlanService;
import com.anolesoft.twelvePlan.vo.GongDuanPlanVO;
import com.anolesoft.twelvePlan.vo.MesEqualCatalogVO;
import com.anolesoft.twelvePlan.vo.PlanCheckVO;
import com.anolesoft.yr.demo.PageResult;
import com.anolesoft.yr.util.PageData;
import com.anolesoft.yr.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zyq
 * @date 2022/3/30
 */
@RestController
@RequestMapping(value="/gongDuanPlan")
@Slf4j
public class GongDuanPlanController {

    @Autowired
    private GongDuanPlanService gongDuanPlanService;

    @PostMapping(value = "/query")
    public AjaxResult queryGDPlan(@RequestBody GongDuanPlanVO gongDuanPlanVO){
        log.debug("gongDuanPlanVO：{}" + gongDuanPlanVO);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        gongDuanPlanVO.setFactoryId(loginUser.getFacCode());
        Integer pageSize = gongDuanPlanVO.getPageSize();
        Integer pageNo = gongDuanPlanVO.getPageNo();
        String waixieString = this.arrayToString(gongDuanPlanVO.getWaixies());
        String plangrade = this.arrayToString(gongDuanPlanVO.getPlangrades());
        gongDuanPlanVO.setWaixie(waixieString);
        gongDuanPlanVO.setPlangrade(plangrade);
        GongDuanPlanDTO gongDuanPlanDTO = BeanUtil.copyProperties(gongDuanPlanVO, GongDuanPlanDTO.class);
        log.debug("gongDuanPlanDTO：{}" + gongDuanPlanDTO);
        PageData<List<GongDuanPlanDTO>> listPageData = this.gongDuanPlanService.queryGDPlan(gongDuanPlanDTO, pageNo, pageSize);
        List<GongDuanPlanVO> gongDuanPlanVOList = listPageData.getItems().stream()
                .map(t -> BeanUtil.copyProperties(t, GongDuanPlanVO.class))
                .collect(Collectors.toList());
        for (int i = 0; i < gongDuanPlanVOList.size(); i++) {
            gongDuanPlanVOList.get(i).setIndex(i + pageSize * (pageNo - 1) + 1);
        }
        PageResult pageResult = new PageResult(gongDuanPlanVOList, pageSize, pageNo, listPageData.getTotal());
        return AjaxResult.success("查询成功", pageResult);
    }


    @PostMapping(value="/export")
    public void exportEqual(@RequestBody GongDuanPlanVO gongDuanPlanVO, HttpServletResponse response){
        long start = System.currentTimeMillis();
        //OutputStream output = null;
        LoginUser loginUser = SecurityUtils.getLoginUser();
        gongDuanPlanVO.setFactoryId(loginUser.getFacCode());
        String waixieString = this.arrayToString(gongDuanPlanVO.getWaixies());
        String plangrade = this.arrayToString(gongDuanPlanVO.getPlangrades());
        gongDuanPlanVO.setWaixie(waixieString);
        gongDuanPlanVO.setPlangrade(plangrade);
        log.debug("gongDuanPlanVO: {}", gongDuanPlanVO);
        GongDuanPlanDTO gongDuanPlanDTO = BeanUtil.copyProperties(gongDuanPlanVO, GongDuanPlanDTO.class);
        log.debug("mesWXInfoDTO: {}", gongDuanPlanDTO);
        try {
            OutputStream output = response.getOutputStream();
            //字符集
            response.setCharacterEncoding("utf-8");
            //类型
            response.setContentType("multipart/form-data");
            //响应头
            response.setHeader("Content-Disposition", "attachment;filename="+new String(("export.xlsx").getBytes("gb2312"),"ISO8859-1"));
            //单个sheet最大条数
            int size = 100000;
            //总条数
            int total = this.gongDuanPlanService.queryGDPlan(gongDuanPlanDTO, 1, 20).getTotal();
            log.debug("total:" + total);
            //sheet数
            int sheet = total / size + 1;
            //单次查询条数
            int pageSize = 1000;
            ExcelWriter excelWriter = EasyExcel.write(output).build();
            //执行查询次数
            int count = 1;
            for (int i = 0; i < sheet ; i++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(i,"工段计划" + (i+1))
                        .head(GongDuanPlanExport.class)
                        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                        .build();
                int rolling;
                if (i == sheet - 1) {
                    rolling = (total - i * size) / pageSize + 1;
                } else {
                    rolling = size / pageSize;
                }
                for (int j = 0; j < rolling; j++) {
                    PageData<List<GongDuanPlanExport>> gdPlan = this.gongDuanPlanService.exportGDPlan(gongDuanPlanDTO, count, pageSize);
                    List<GongDuanPlanExport> datas = gdPlan.getItems();
                    excelWriter.write(datas, writeSheet);
                    count++;
                }
            }
            log.debug("查询次数：" + (count - 1) + "次");
            //刷新流
            excelWriter.finish();
            output.flush();
            response.getOutputStream().close();
        } catch (Exception e) {
            log.error("导出失败：{}", e.getMessage());
            e.printStackTrace();
        } finally {
            long end = System.currentTimeMillis();
            log.debug("总用时：" + (end - start) + "毫秒");
        }
    }

    /**
     * 下拉选多选数组转模糊查询字符串
     * @param array
     * @return
     */
    private String arrayToString(String[] array) {
        StringBuffer str = new StringBuffer();
        if (array != null && array.length > 0) {
            for (String s: array) {
                str.append("'");
                str.append(s);
                str.append("',");
            }
        }
        if (str.length() > 1) {
            str.setLength(str.length()-1);
        }
        log.debug("字符串数组转字符串结果：" + str.toString());
        return str.toString();
    }
}
